package cn.janus.pojo.vo;

import cn.janus.pojo.po.BillPO;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
public class BillForMonthVO {
    List<CategoryVO> categoryVOS;
    List<BillVO> billVOS;

    public BillForMonthVO(List<BillPO> billPOS) {
        billVOS = new ArrayList<>();
        categoryVOS = new ArrayList<>();
        for (BillPO billPO : billPOS) {
            addCategoryVO(billPO);
            BillVO billVO = new BillVO();
            BeanUtils.copyProperties(billPO, billVO);
            billVOS.add(billVO);
        }
        BigDecimal total = new BigDecimal(0);
        for (CategoryVO categoryVO : categoryVOS) {
            if (!categoryVO.getCategory().equals("收入")) {
                total = total.add(categoryVO.getAmount());
            }
        }
        for (CategoryVO categoryVO : categoryVOS) {
            if (categoryVO.getCategory().equals("收入")) {
                if ((categoryVO.getAmount().compareTo(total)) > 0) {
                    categoryVO.setPercent("收支平衡");
                } else {
                    categoryVO.setPercent("入不敷出");
                }
            } else {
                categoryVO.setPercent(categoryVO.getAmount()
                        .multiply(new BigDecimal(100))
                        .divide(total, 2, RoundingMode.HALF_EVEN) + "%");
            }
        }
    }

    /**
     * 统计分类
     */
    public void addCategoryVO(BillPO billPO) {
        for (CategoryVO categoryVO : categoryVOS) {
            if (categoryVO.getCategory().equals(billPO.getCategory())) {
                BigDecimal result = categoryVO.getAmount().add(billPO.getAmount());
                categoryVO.setAmount(result);
                return;
            }
        }
        CategoryVO categoryVO = new CategoryVO();
        categoryVO.setCategory(billPO.getCategory());
        categoryVO.setAmount(billPO.getAmount());
        categoryVOS.add(categoryVO);
    }
}
